package cn.jvtc.course.management.system.utils;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import net.sourceforge.tess4j.util.ImageHelper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 爬取课表
 *
 * @author GaoFeng2017
 * @date 2017-12-07 12:27:57
 **/

public class InternetWorm {
    static Pattern pr = Pattern.compile("(<td valign=top width=\\'13\\%\\'>).*(<\\/td>)");
    static Pattern pr2 = Pattern.compile("(<td  width=80% align=left >).+(</td>)");
    private static int id;

    static{
        Properties p = new Properties();
        try {
            InputStream in = Class.forName("cn.jvtc.course.management.system.utils.InternetWorm").getClassLoader().getResourceAsStream("tid.properties");
            p.load(in);
            System.out.println("当前教师id" + p.getProperty("id"));
            id = Integer.parseInt(p.getProperty("id"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
        try {
            //重置id
            int i = 0;
//            System.out.println(i++ + "");
            changeId(100);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void changeId(int id) throws ClassNotFoundException, IOException {
        Properties properties = new Properties();
        properties.setProperty("id",id + "");
//        System.out.println(Class.forName("cn.jvtc.course.management.system.utils.InternetWorm").getClassLoader().getResource("tid.properties"));
        OutputStream io = new FileOutputStream(Class.forName("cn.jvtc.course.management.system.utils.InternetWorm").getClassLoader().getResource("tid.properties").getPath());
        properties.store(io,null);
    }

    public static int createTable(String captcha,String sid) throws Exception{
        String content = null;
        FileOutputStream fos = new FileOutputStream(Class.forName("cn.jvtc.course.management.system.utils.InternetWorm").getClassLoader().getResource("class_table.txt").getPath(),true);
        while(!(content = getContent(id + "",sid,captcha)).contains("验证码错误")) {
            changeId(id);
            if (!content.contains("部门")) {
                System.out.println(id + "不是老师");
                fos.write((id + "不是老师\r\n").getBytes());
                id++;
                continue;
            }
            content = content.replaceAll("</tr>","</tr>\n");
            content = content.replaceAll("</td>","</td>\n");
            content = content.replaceAll("</TD>","</TD>\n");
            content = content.replaceAll("([</tr>,</TD>,</td>])","$1\n");

            content = content.replaceAll("<br>","");
            content = content.replaceAll("&nbsp;"," ");
            content = content.replaceAll("；","");
            content = content.replaceAll("]","] ");
            content = content.replaceAll("\\)",") ");
            content = content.replaceAll("人数"," 人数");
//            System.out.println(content);

            //获取匹配器对象
            Matcher mt = pr2.matcher(content);

            //课表信息
            String title = "";
            if(mt.find()){
                title = mt.group();
                title = title.replace("<td  width=80% align=left >","");
                title = title.replace("</td>"," ");
                System.out.println(title);
            }

            mt = pr.matcher(content);
            //课表内容
            int count = 0;
            int index = 0;
            String[] week = new String[]{"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
            String[][] table = new String[7][5];
            while(mt.find())
            {
                String column = mt.group();
                column = column.replace("<td valign=top width='13%'>","");
                column = column.replace("</td>"," ");
                count++;
                if(count % 7 == 0) {
                    index++;
                }

                if(!"".equals(column.trim())) {
//                    String str = "(" + week[count%7] + ")";
                    table[count%7][index] = column;
                }


            }
            /*for(String[] strs : table) {
                System.out.println(Arrays.toString(strs));
            }*/

            //分割标题
            String[] arr = title.split("  ");
            String dep = arr[0].substring(3);
            String th = arr[1].substring(3);
            String sex = arr[2].substring(3);
            //写入properties
            Properties pro = new Properties();
            pro.setProperty("部门",dep);
            pro.setProperty("教师",th);
            pro.setProperty("性别",sex);
            pro.setProperty("tid",id + "");
//            System.out.println(th);
            for(int i = 0;i < table.length;i++) {
                StringBuilder sb = new StringBuilder();
                for(String s : table[i]) {
                    if(s!=null) {
                        sb.append(s).append(",");
                    }
                }
                pro.setProperty(week[i],sb.toString());
            }

            OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream("H:\\table_class\\" + th + ".properties"),"utf-8");
            pro.store(ow,"");
            ow.close();
            System.out.println(th + "老师信息录入完毕\r\n");
            fos.write((id + th + "老师信息录入完毕\r\n").getBytes());
            id++;
        }

        fos.close();
        return id;
    }
    public static void OCRCaptcha() throws TesseractException {
        ITesseract instance = new Tesseract();
        //如果未将tessdata放在根目录下需要指定绝对路径
        instance.setDatapath("H:\\API\\API\\soft_package\\Tess4J-3.4.2-src\\tessdata");
        // 我们需要指定识别语种
        instance.setLanguage("eng");

        // 指定识别图片
        File imgDir = new File("H:\\code.jpg");
        //二值化
        BufferedImage grayImage = null;
        try {
            grayImage = ImageHelper.convertImageToBinary(ImageIO.read(imgDir));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ImageIO.write(grayImage, "jpg", imgDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long startTime = System.currentTimeMillis();
        String ocrResult = instance.doOCR(imgDir);
        // 输出识别结果
        System.out.println("OCR Result: \n" + ocrResult + "\n 耗时：" + (System.currentTimeMillis() - startTime) + "ms");
    }
    /**
     * @description:
     * @author: GaoFeng2017
     * @date: 2017/12/7 21:58
     * @param: [id, sessionId, captcha]
     * @return: java.lang.String
     *
     */
    public static String getContent(String id,String sessionId,String captcha) throws Exception {

        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();

        try {
            String url = "http://218.65.5.214:2001/jwweb/ZNPK/TeacherKBFB_rpt.aspx";
            HttpPost httpPost = new HttpPost(url);
            //设置防外链头信息
            httpPost.setHeader("referer", "http://218.65.5.214:2001/jwweb/ZNPK/TeacherKBFB.aspx");

            //cookie
            BasicClientCookie cookie = new BasicClientCookie("ASP.NET_SessionId", sessionId);
            cookie.setVersion(0);
            cookie.setDomain("218.65.5.214");
            cookie.setPath("/");
            cookieStore.addCookie(cookie);

            //建立HttpPost对象
            List<NameValuePair> params = new ArrayList<>();

            //建立一个NameValuePair数组，用于存储欲传送的参数
            params.add(new BasicNameValuePair("Sel_XNXQ", "20170"));
            params.add(new BasicNameValuePair("Sel_JS", "000" + id));
            params.add(new BasicNameValuePair("type", "1"));
            params.add(new BasicNameValuePair("txt_yzm", captcha));

            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));


            CloseableHttpResponse response = httpclient.execute(httpPost);
            List<Cookie> cookies = cookieStore.getCookies();

            /*for (int i = 0; i < cookies.size(); i++) {
                System.out.println("Local cookie: " + cookies.get(i));
            }*/

            try {
                HttpEntity entity = response.getEntity();
                //打印目标网站输出内容
                String content =  EntityUtils.toString(entity);
                EntityUtils.consume(entity);

                return content;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}
